﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace V32Assembler
{
    public static class CmdLineOptions
    {
        public static IEnumerable<string> Get(string[] args, IEnumerable<Tuple<char, string, Action>> options)
        {
            List<int> optionArgs = new List<int>(args.Length);
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                if (arg.StartsWith("-") && !arg.StartsWith("--"))
                {
                    if (arg.Length == 1)
                        throw new CmdLineOptionException("A dash ('-') must be followed by one or more abbreviated option names.");
                    foreach (char abbrev in arg.Substring(1))
                    {
                        bool foundOption = false;
                        foreach (var option in options)
                        {
                            if (abbrev == option.Item1)
                            {
                                foundOption = true;
                                option.Item3();
                                break;
                            }
                        }
                        if (!foundOption) throw new CmdLineOptionException("Unknown abbreviated option '" + abbrev + "'.");
                    }
                    optionArgs.Add(i);
                }
                else if (arg.StartsWith("--"))
                {
                    if (arg.Length == 2)
                        throw new CmdLineOptionException("A double dash ('--') must be followed by an option name.");
                    arg = arg.Substring(2);
                    bool foundOption = false;
                    foreach (var option in options)
                    {
                        if (arg == option.Item2)
                        {
                            foundOption = true;
                            option.Item3();
                            break;
                        }
                    }
                    if (!foundOption) throw new CmdLineOptionException("Unknown option '" + arg + "'.");
                    optionArgs.Add(i);
                }
            }
            return args.Where((arg, index) => !optionArgs.Contains(index));
        }
    }
    public class CmdLineOptionException : Exception
    {
        public CmdLineOptionException(string message) : base(message) { }
    }
}
